#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @Time    : 2025/9/27 16:38
# @Author  : WXY
# @File    : SetCookies
# @PROJECT_NAME: youtubedown_gui
# @PRODUCT_NAME: PyCharm
# -------------------------------------------------------------------------------

from PySide6.QtWidgets import QMainWindow, QMessageBox
from PySide6.QtCore import Qt, Slot

from py.CookiesHelper import CookiesHelperWindow
from py_gui.setcookies_ui import Ui_SetCookies
from LoggerManager import logger_manager
from utils import setup_window_icon, setup_window_title, show_info, show_error, show_warning, SCROLLBARSTYLE
import os

class SetCookiesWindow(QMainWindow):
    """Cookies设置窗口"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_SetCookies()
        self.ui.setupUi(self)

        # 初始化帮助窗口
        self.cookies_helper_window = None

        # 设置窗口属性
        self.setup_window()

        # 连接信号槽
        self.connect_signals()

        # 设置样式
        self.setup_styles()

        # 加载现有cookies
        self.load_existing_cookies()
        
    def setup_window(self):
        """设置窗口属性"""
        try:
            # 设置窗口图标和标题
            setup_window_icon(self)
            setup_window_title(self, "Cookies设置")
             
           # 使用getattr来兼容不同版本
            window_flags = (
                getattr(Qt, 'Window', Qt.WindowType.Window) |
                getattr(Qt, 'WindowCloseButtonHint', Qt.WindowType.WindowCloseButtonHint) |
                getattr(Qt, 'WindowMinimizeButtonHint', Qt.WindowType.WindowMinimizeButtonHint)
            )
            self.setWindowFlags(window_flags)
            self.setFixedSize(600, 400)  # 固定窗口大小
            
            logger_manager.info("✅ Cookies设置窗口初始化完成", "SetCookies")
            
        except Exception as e:
            logger_manager.error(f"设置窗口属性失败: {e}", "SetCookies")
            
    def connect_signals(self):
        """连接信号槽"""
        try:
            # 连接按钮信号
            self.ui.btn_start.clicked.connect(self.confirm_cookies)
            self.ui.btn_clear_url.clicked.connect(self.clear_content)
            self.ui.pushButton_2.clicked.connect(self.show_help)
            
            logger_manager.info("✅ 信号槽连接完成", "SetCookies")
            
        except Exception as e:
            logger_manager.error(f"连接信号槽失败: {e}", "SetCookies")
            
    def setup_styles(self):
        """设置样式"""
        try:
            # 设置字符画文本
            self.setup_character_art_texts()
            # 应用滚动条样式到textEdit_debug
            if hasattr(self.ui, 'textEdit_cookies'):
                scrollbar = self.ui.textEdit_cookies.verticalScrollBar()
                if scrollbar:
                    scrollbar.setStyleSheet(SCROLLBARSTYLE)
                    logger_manager.info("✅ 滚动条样式应用成功", "SetCookies")

        except Exception as e:
            logger_manager.error(f"设置样式失败: {e}", "SetCookies")

    def setup_character_art_texts(self):
        """设置字符画文本，避免在UI文件中硬编码"""
        try:
            # 设置按钮文本
            if hasattr(self.ui, 'pushButton_2'):  # 查看帮助按钮
                self.ui.pushButton_2.setText("📖 查看帮助")

            if hasattr(self.ui, 'btn_clear_url'):  # 清空内容按钮
                self.ui.btn_clear_url.setText("🗑️ 清空内容")

            if hasattr(self.ui, 'btn_start'):  # 保存cookies按钮
                self.ui.btn_start.setText("🍪 保存Cookies")

            # # 设置标题文本
            # if hasattr(self.ui, 'titleLabel'):
            #     self.ui.titleLabel.setText("🍪 Cookies设置")

            # 设置说明文本
            if hasattr(self.ui, 'lbl_set_text_2'):
                self.ui.lbl_set_text_2.setText("请在下方文本框中输入您的YouTube Cookies")

            logger_manager.info("✅ 字符画文本设置完成", "SetCookies")

        except Exception as e:
            logger_manager.error(f"设置字符画文本失败: {e}", "SetCookies")

    def load_existing_cookies(self):
        """加载现有的cookies"""
        try:
            cookies_file = "cookies.txt"
            if os.path.exists(cookies_file):
                with open(cookies_file, 'r', encoding='utf-8') as f:
                    cookies_content = f.read().strip()
                    if cookies_content:
                        self.ui.textEdit_cookies.setPlainText(cookies_content)
                        logger_manager.info("✅ 已加载现有cookies", "SetCookies")
                    else:
                        self.ui.textEdit_cookies.setPlainText("# 请在此处粘贴您的YouTube cookies\n# 格式示例：\n# name=value; domain=.youtube.com; path=/\n")
            else:
                self.ui.textEdit_cookies.setPlainText("# 请在此处粘贴您的YouTube cookies\n# 格式示例：\n# name=value; domain=.youtube.com; path=/\n")
                logger_manager.info("📝 显示cookies输入提示", "SetCookies")
                
        except Exception as e:
            logger_manager.error(f"加载cookies失败: {e}", "SetCookies")
            self.ui.textEdit_cookies.setPlainText("# 请在此处粘贴您的YouTube cookies\n")
            
    @Slot()
    def confirm_cookies(self):
        """确认并保存cookies"""
        try:
            # 1. 判断textEdit_debug是否为空或全是#开头的内容
            cookies_content = self.ui.textEdit_cookies.toPlainText().strip()

            if not cookies_content:
                show_warning(self, "警告", "请输入cookies内容！")
                return

            # 检查是否全是注释行
            lines = cookies_content.split('\n')
            valid_lines = [line.strip() for line in lines if line.strip() and not line.strip().startswith('#')]

            if not valid_lines:
                show_warning(self, "警告", "请输入有效的cookies内容！\n当前只有注释行，没有实际的cookies数据。")
                return

            # 2. 在当前根目录下写cookies.txt文件（覆盖写入）
            cookies_file = "cookies.txt"
            with open(cookies_file, 'w', encoding='utf-8') as f:
                f.write(cookies_content)

            logger_manager.info("✅ Cookies保存成功", "SetCookies", show_in_ui=True)
            show_info(self, "成功", f"Cookies已成功保存到 {cookies_file}！\n共保存了 {len(valid_lines)} 行有效数据。")
            
            # 关闭窗口
            self.close()
            
        except Exception as e:
            error_msg = f"保存cookies失败: {e}"
            logger_manager.error(error_msg, "SetCookies", show_in_ui=True)
            show_error(self, "错误", error_msg)
            
    @Slot()
    def clear_content(self):
        """清空内容"""
        try:
            # 先检查内容是否为空
            current_content = self.ui.textEdit_cookies.toPlainText().strip()
            
            # 如果内容为空或只有注释，直接返回
            if not current_content: # or current_content.startswith("#"):
                logger_manager.info("📝 内容已为空，无需清空", "SetCookies")
                return
            
            # 使用封装好的show_confirm函数
            from utils import show_confirm
            
            reply = show_confirm(
                self, 
                "确认清空", 
                "确定要清空所有内容吗？"
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                self.ui.textEdit_cookies.clear()
                logger_manager.info("🗑️ 已清空cookies内容", "SetCookies")
                
        except Exception as e:
            logger_manager.error(f"清空内容失败: {e}", "SetCookies")

    @Slot()
    def show_help(self):
        """显示帮助信息"""
        try:
            # 如果帮助窗口不存在或已被关闭，创建新的窗口
            if self.cookies_helper_window is None or not self.cookies_helper_window.isVisible():
                self.cookies_helper_window = CookiesHelperWindow(self)

            # 显示窗口并置于前台
            self.cookies_helper_window.show()
            self.cookies_helper_window.raise_()
            self.cookies_helper_window.activateWindow()

            logger_manager.info("📖 显示Cookies帮助窗口", "SetCookies")

        except Exception as e:
            logger_manager.error(f"显示帮助窗口失败: {e}", "SetCookies")

    def closeEvent(self, event):
        """窗口关闭事件"""
        try:
            logger_manager.info("🔒 Cookies设置窗口已关闭", "SetCookies")
            event.accept()
        except Exception as e:
            logger_manager.error(f"关闭窗口失败: {e}", "SetCookies")
            event.accept()